<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 旅行家</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome 图标 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .profile-card {
            border-radius: 15px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        .avatar-container {
            position: relative;
            width: 150px;
            height: 150px;
            margin: 0 auto 20px;
        }
        .avatar-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid #fff;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .avatar-upload {
            position: absolute;
            bottom: 0;
            right: 0;
            background: #0d6efd;
            color: white;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        .info-label {
            font-weight: 600;
            color: #495057;
        }
        .info-value {
            color: #212529;
        }
        .edit-btn {
            cursor: pointer;
            color: #0d6efd;
        }
        .status-active {
            color: #198754;
        }
        .status-inactive {
            color: #dc3545;
        }
        .level-badge {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
        }

        /* 删除账号按钮样式 */
        .text-danger {
            color: #dc3545 !important;
        }
        .btn-danger {
            background-color: #dc3545;
            border-color: #dc3545;
        }
        .btn-danger:hover {
            background-color: #bb2d3b;
            border-color: #b02a37;
        }

    </style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
    <div class="container">
        <a class="navbar-brand" href="/index1.html">
            <i class="fas fa-compass me-2"></i>旅行家
        </a>
        <div class="d-flex" id="userNav">
            <div class="dropdown">
                <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" id="dropdownUser" data-bs-toggle="dropdown" aria-expanded="false">
                    <img id="navAvatar" src="" alt="用户头像" width="32" height="32" class="rounded-circle me-2">
                    <span id="navUsername"></span>
                </a>
                <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownUser">
                    <li><a class="dropdown-item active" href="/lv-index/index1.html"><i class="fas fa-user-circle me-2"></i>首页</a></li>
                    <li><a class="dropdown-item" href="#"><i class="fas fa-heart me-2"></i>我的收藏</a></li>
                    <li><a class="dropdown-item" href="#"><i class="fas fa-book me-2"></i>我的游记</a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item text-danger" href="#" id="deleteAccountBtn"><i class="fas fa-user-slash me-2"></i>注销账号</a></li>
                    <li><a class="dropdown-item" href="/lv-index/index.html" id="logoutBtn"><i class="fas fa-sign-out-alt me-2"></i>退出登录</a></li>
                </ul>
            </div>
        </div>
    </div>
</nav>

<div class="container py-5">
    <div class="row">
        <div class="col-lg-4">
            <div class="card profile-card mb-4">
                <div class="card-body text-center">
                    <div class="avatar-container">
                        <img id="userAvatar" src="" class="avatar-img">
                        <div class="avatar-upload" data-bs-toggle="modal" data-bs-target="#avatarModal">
                            <i class="fas fa-camera"></i>
                        </div>
                    </div>
                    <h3 id="userName" class="mb-2"></h3>
                    <p class="text-muted mb-3"><span id="userLevel" class="badge level-badge"></span></p>
                    <p class="text-muted mb-4" id="userBio"></p>
                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editBioModal">
                        <i class="fas fa-edit me-1"></i>编辑简介
                    </button>
                </div>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="card profile-card">
                <div class="card-header bg-white">
                    <h5 class="mb-0"><i class="fas fa-info-circle me-2 text-primary"></i>基本信息</h5>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <p class="mb-2"><span class="info-label"><i class="fas fa-user me-2"></i>用户名:</span>
                                <span id="displayName" class="info-value"></span>
                                <a href="#" class="edit-btn ms-2" data-bs-toggle="modal" data-bs-target="#editNameModal">
                                    <i class="fas fa-edit"></i>
                                </a>
                            </p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-2"><span class="info-label"><i class="fas fa-at me-2"></i>账号:</span>
                                <span id="userAccount" class="info-value"></span>
                            </p>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <p class="mb-2"><span class="info-label"><i class="fas fa-venus-mars me-2"></i>性别:</span>
                                <span id="userGender" class="info-value"></span>
                                <a href="#" class="edit-btn ms-2" data-bs-toggle="modal" data-bs-target="#editGenderModal">
                                    <i class="fas fa-edit"></i>
                                </a>
                            </p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-2"><span class="info-label"><i class="fas fa-birthday-cake me-2"></i>生日:</span>
                                <span id="userBirthday" class="info-value"></span>
                                <a href="#" class="edit-btn ms-2" data-bs-toggle="modal" data-bs-target="#editBirthdayModal">
                                    <i class="fas fa-edit"></i>
                                </a>
                            </p>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <p class="mb-2"><span class="info-label"><i class="fas fa-envelope me-2"></i>邮箱:</span>
                                <span id="userEmail" class="info-value"></span>
                                <a href="#" class="edit-btn ms-2" data-bs-toggle="modal" data-bs-target="#editEmailModal">
                                    <i class="fas fa-edit"></i>
                                </a>
                            </p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-2"><span class="info-label"><i class="fas fa-check-circle me-2"></i>账号状态:</span>
                                <span id="userStatus" class="info-value"></span>
                            </p>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <p class="mb-2"><span class="info-label"><i class="fas fa-calendar-plus me-2"></i>创建时间:</span>
                                <span id="createTime" class="info-value"></span>
                            </p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-2"><span class="info-label"><i class="fas fa-calendar-check me-2"></i>更新时间:</span>
                                <span id="updateTime" class="info-value"></span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 修改头像模态框 -->
<div class="modal fade" id="avatarModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改头像</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center">
                <div class="row">
                    <div class="col-3">
                        <img src="img/boy1.png" class="img-fluid rounded-circle mb-2 head-option" data-head="boy1" style="cursor: pointer;">
                    </div>
                    <div class="col-3">
                        <img src="img/boy2.png" class="img-fluid rounded-circle mb-2 head-option" data-head="boy2" style="cursor: pointer;">
                    </div>
                    <div class="col-3">
                        <img src="img/girl1.png" class="img-fluid rounded-circle mb-2 head-option" data-head="girl1" style="cursor: pointer;">
                    </div>
                    <div class="col-3">
                        <img src="img/girl2.png" class="img-fluid rounded-circle mb-2 head-option" data-head="girl2" style="cursor: pointer;">
                    </div>
                </div>
                <div class="mt-3">
                    <button type="button" class="btn btn-primary" id="saveAvatarBtn">保存更改</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 编辑简介模态框 -->
<div class="modal fade" id="editBioModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑个人简介</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <textarea id="bioInput" class="form-control" rows="5" placeholder="介绍一下你自己..."></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveBioBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑用户名模态框 -->
<div class="modal fade" id="editNameModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改用户名</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="nameInput" class="form-label">新用户名</label>
                    <input type="text" class="form-control" id="nameInput">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveNameBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑性别模态框 -->
<div class="modal fade" id="editGenderModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改性别</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="gender" id="male" value="1">
                    <label class="form-check-label" for="male">男</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="gender" id="female" value="2">
                    <label class="form-check-label" for="female">女</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="gender" id="secret" value="0">
                    <label class="form-check-label" for="secret">保密</label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveGenderBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑生日模态框 -->
<div class="modal fade" id="editBirthdayModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改生日</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="birthdayInput" class="form-label">选择生日</label>
                    <input type="date" class="form-control" id="birthdayInput">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveBirthdayBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑邮箱模态框 -->
<div class="modal fade" id="editEmailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改邮箱</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="emailInput" class="form-label">新邮箱地址</label>
                    <input type="email" class="form-control" id="emailInput">
                </div>
                <div class="mb-3">
                    <label for="emailCode" class="form-label">验证码</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="emailCode" placeholder="请输入验证码">
                        <button class="btn btn-outline-secondary" type="button" id="sendCodeBtn">发送验证码</button>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveEmailBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除账号确认模态框 -->
<div class="modal fade" id="deleteAccountModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>确认注销账号</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger">
                    <strong>警告！</strong> 此操作将永久删除您的账号和所有数据，且无法恢复！
                </div>
                <p>请输入您的密码以确认注销：</p>
                <input type="password" class="form-control" id="confirmPassword" placeholder="请输入密码">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认注销</button>
            </div>
        </div>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    // // 从localStorage获取用户基本信息
    let userInfo = JSON.parse(localStorage.getItem('userInfo'));
    if (!userInfo) {
        window.location.href = '/index.html';
    }

    // 立即显示用户信息
    renderUserInfo(userInfo);

    // 从服务器获取最新信息
    fetchUserInfo(userInfo.zhanghao);

    console.log('User info:', userInfo);

    // 获取完整用户信息
    function fetchUserInfo() {
        if (!userInfo || !userInfo.zhanghao) {
            console.error('无用户账号信息');
            return;
        }

        console.log('正在获取用户信息，账号:', userInfo.zhanghao);

        axios.get('/lvuser/info', {
            params: {
                zhanghao: userInfo.zhanghao
            }
        }).then(response => {
            console.log('服务器响应:', response.data);

            if (response.data.code === 1) {
                let userData = response.data.data;

                if (Array.isArray(userData) && userData.length > 0){
                    if (userData.length > 0){
                        userData = userData[0]; //取第一个用户
                    }else {
                        throw new Error('未找到用户信息');
                    }
                }

                //只使用从服务器获取数据
                userInfo = userData;
                localStorage.setItem('userInfo', JSON.stringify(userInfo));
                //渲染用户信息
                renderUserInfo();
            } else {
                alert('获取用户信息失败: ' + response.data.msg);
            }
        }).catch(error => {
            console.error('获取用户信息错误:', error);
            alert('获取用户信息失败: ' + error.message);

            //如果本地有数据，使用本地数据渲染
            if (userInfo){
                renderUserInfo();
            }else {
                location.href = "/lv-index/index.html";
            }
        });
    }

    // 时间格式化函数
    function formatDateTime(dateTimeStr) {
        if (!dateTimeStr) {
            console.warn('时间字符串为空');
            return '未知';
        }

        try {
            // 处理只有日期没有时间的情况
            if (/^\d{4}-\d{2}-\d{2}$/.test(dateTimeStr)) {
                return dateTimeStr; // 直接返回日期部分
            }

            const date = new Date(dateTimeStr);
            if (isNaN(date.getTime())) {
                console.warn('无法解析时间字符串:', dateTimeStr);
                return '未知';
            }

            // 格式化为"YYYY-MM-DD"
            const pad = num => num.toString().padStart(2, '0');
            return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())}`;
        } catch (e) {
            console.error('时间格式化错误:', e, '原始值:', dateTimeStr);
            return '未知';
        }
    }

    // 渲染用户信息
    function renderUserInfo() {
        if (!userInfo) return;

        // 填充用户信息
        //头像，如果为空则显示默认头像
        const avatarPath = userInfo.head.startsWith('img/') ?
            userInfo.head : `img/${userInfo.head}`;

        document.getElementById('userAvatar').src = avatarPath;
        document.getElementById('navAvatar').src = avatarPath;

        //用户名
        document.getElementById('userName').textContent = userInfo.uname || '未设置';
        document.getElementById('navUsername').textContent = userInfo.uname || '未设置';
        document.getElementById('displayName').textContent = userInfo.uname || '未设置';

        //账号
        document.getElementById('userAccount').textContent = userInfo.zhanghao || '未设置';

        // 性别转换
        const genderMap = {0: '未知', 1: '男', 2: '女'};
        document.getElementById('userGender').textContent = genderMap[userInfo.gender] || '未设置';

        //邮箱
        document.getElementById('userEmail').textContent = userInfo.email || '未设置';

        // 账号状态
        const statusElement = document.getElementById('userStatus');
        statusElement.textContent = userInfo.status === 0 ? '正常' : '已禁用';
        statusElement.classList.add(userInfo.status === 0 ? 'status-active' : 'status-inactive');

        //账号等级
        document.getElementById('userLevel').textContent = userInfo.level ? `Lv.${userInfo.level}` : 'Lv.0';

        // 时间信息 - 正确的显示方式
        const createTime = userInfo.createAt || '';
        const updateTime = userInfo.updateAt || '';

        console.log('创建时间:', createTime);
        console.log('更新时间:', updateTime);

        document.getElementById('createTime').textContent = formatDateTime(createTime);
        document.getElementById('updateTime').textContent = formatDateTime(updateTime);

        //生日信息
        document.getElementById('userBirthday').textContent = userInfo.birthday || '未设置';

        //简介
        document.getElementById('userBio').textContent = userInfo.bio || '这个人很懒，什么都没留下...';
        document.getElementById('bioInput').value = userInfo.bio || '';

        // 设置性别选择
        if (userInfo.gender !== undefined) {
            document.querySelector(`input[name="gender"][value="${userInfo.gender}"]`).checked = true;
        }

        // 设置生日输入
        if (userInfo.birthday) {
            document.getElementById('birthdayInput').value = userInfo.birthday;
        }

        // 初始化模态框中的当前值
        document.getElementById('nameInput').value = userInfo.uname || '';
        document.getElementById('emailInput').value = userInfo.email || '';

    }

    // 更新用户信息到服务器
    function updateUserInfo(field, value) {
        //确保值有效
        if (!field) {
            console.error('field参数不能为空');
            return;
        }
        const updateData = {
            zhanghao: userInfo.zhanghao,
            field: field,
            value: value
        };

        //空字符串处理（根据后端请求）
        if (updateData[field] === ''){
            updateData[field] = null; //或者改为默认值
        }

        //添加请求拦截器
        axios.interceptors.request.use(config => {
            console.log('发送请求：',config.data);
            return config;
        });

        // 添加响应拦截器
        axios.interceptors.response.use(response => {
            console.log('收到响应:', response.data);
            return response;
        }, error => {
            console.error('请求错误:', error);
            return Promise.reject(error);
        });

        axios.post('/lvuser/update', updateData, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            transformRequest: [function(data) {
                let ret = '';
                for (let it in data) {
                    if(data[it] !== null && data[it] !== undefined){
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                    }
                }
                return ret;
            }]
        }).then(response => {
            if (response.data.code === 1) {
                // 更新本地存储
                userInfo[field] = value;
                userInfo['update_at'] = new Date().toISOString().slice(0, 19).replace('T', ' ');
                localStorage.setItem('userInfo', JSON.stringify(userInfo));
                renderUserInfo();
                alert("更新成功")
            } else {
                alert('更新失败: ' + response.data.msg);
            }
        }).catch(error => {
            console.error('更新用户信息错误:', error);
            alert('更新失败：' + (error.response?.data?.message || error.message));
        });
    }

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        if (!userInfo) {
            window.location.href = '/lv-index/index.html';
            return;
        }

        // 获取完整用户信息
        fetchUserInfo();

        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', function(e) {
            e.preventDefault();
            localStorage.removeItem('userInfo');
            window.location.href = '/lv-index/index.html';
        });

        // 头像选择事件 - 修正类名
        document.querySelectorAll('.head-option').forEach(head => {
            head.addEventListener('click', function() {
                document.querySelectorAll('.head-option').forEach(a => a.classList.remove('border', 'border-primary'));
                this.classList.add('border', 'border-primary');
            });
        });

        // 保存头像 - 修正逻辑
        document.getElementById('saveAvatarBtn').addEventListener('click', function() {
            const selectedAvatar = document.querySelector('.head-option.border-primary');
            if (selectedAvatar) {
                const headNum = selectedAvatar.getAttribute('data-head');
                const newHead = `img/${headNum}.png`;  // 修正路径格式
                updateUserInfo('head', newHead);
                bootstrap.Modal.getInstance(document.getElementById('avatarModal')).hide();
            } else {
                alert('请先选择一个头像');
            }
        });

        // 保存简介
        document.getElementById('saveBioBtn').addEventListener('click', function() {
            const newBio = document.getElementById('bioInput').value;
            updateUserInfo('bio', newBio);
            bootstrap.Modal.getInstance(document.getElementById('editBioModal')).hide();
        });

        // 保存用户名
        document.getElementById('saveNameBtn').addEventListener('click', function() {
            const newName = document.getElementById('nameInput').value.trim();
            if (newName) {
                updateUserInfo('uname', newName);
                bootstrap.Modal.getInstance(document.getElementById('editNameModal')).hide();
            } else {
                alert('用户名不能为空');
            }
        });

        // 保存性别
        document.getElementById('saveGenderBtn').addEventListener('click', function() {
            const selectedGender = document.querySelector('input[name="gender"]:checked');
            if (selectedGender) {
                updateUserInfo('gender', parseInt(selectedGender.value));
                bootstrap.Modal.getInstance(document.getElementById('editGenderModal')).hide();
            }
        });

        // 保存生日
        document.getElementById('saveBirthdayBtn').addEventListener('click', function() {
            const newBirthday = document.getElementById('birthdayInput').value;
            if (newBirthday) {
                updateUserInfo('birthday', newBirthday);
                bootstrap.Modal.getInstance(document.getElementById('editBirthdayModal')).hide();
            }
        });

        // 发送验证码
        document.getElementById('sendCodeBtn').addEventListener('click', function() {
            const email = document.getElementById('emailInput').value;
            if (!email) {
                alert('请输入邮箱地址');
                return;
            }

            axios.post('/lvuser/send-code', {
                email: email
            }).then(response => {
                if (response.data.code === 1) {
                    alert('验证码已发送');
                    // 禁用按钮60秒
                    this.disabled = true;
                    let countdown = 60;
                    const timer = setInterval(() => {
                        this.textContent = `${countdown}秒后重新发送`;
                        countdown--;
                        if (countdown < 0) {
                            clearInterval(timer);
                            this.disabled = false;
                            this.textContent = '发送验证码';
                        }
                    }, 1000);
                } else {
                    alert('发送验证码失败: ' + response.data.msg);
                }
            }).catch(error => {
                console.error('发送验证码错误:', error);
                alert('发送验证码失败');
            });
        });

        // 保存邮箱
        document.getElementById('saveEmailBtn').addEventListener('click', function() {
            const newEmail = document.getElementById('emailInput').value.trim();
            const code = document.getElementById('emailCode').value.trim();

            if (!newEmail) {
                alert('请输入邮箱地址');
                return;
            }

            if (!code) {
                alert('请输入验证码');
                return;
            }

            axios.post('/lvuser/verify-code', {
                email: newEmail,
                code: code,
                zhanghao: userInfo.zhanghao
            }).then(response => {
                if (response.data.code === 1) {
                    updateUserInfo('email', newEmail);
                    bootstrap.Modal.getInstance(document.getElementById('editEmailModal')).hide();
                } else {
                    alert('验证失败: ' + response.data.msg);
                }
            }).catch(error => {
                console.error('验证邮箱错误:', error);
                alert('验证失败');
            });
        });
    });

    //用户注销
    // 1. 添加删除账号按钮点击事件
    document.getElementById('deleteAccountBtn').addEventListener('click', function(e) {
        e.preventDefault();
        // 显示确认模态框
        const deleteModal = new bootstrap.Modal(document.getElementById('deleteAccountModal'));
        deleteModal.show();
    });

    // 2. 确认删除账号逻辑
    document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
        const password = document.getElementById('confirmPassword').value.trim();

        if (!password) {
            alert('请输入密码确认');
            return;
        }

        if (!confirm('最终确认：您确定要永久删除账号吗？此操作不可撤销！')) {
            return;
        }

        // 显示加载状态
        this.disabled = true;
        this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';

        // 发送删除请求到服务器
        axios.post('/lvuser/delete', {
            zhanghao: userInfo.zhanghao,
            password: password
        }, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(response => {
            if (response.data.code === 1) {
                alert('账号已成功注销');
                // 清除本地数据
                localStorage.removeItem('userInfo');
                // 跳转到首页
                window.location.href = '/lv-index/index.html';
            } else {
                alert('注销失败: ' + response.data.msg);
            }
        }).catch(error => {
            console.error('注销账号错误:', error);
            alert('注销失败: ' + (error.response?.data?.message || error.message));
        }).finally(() => {
            // 恢复按钮状态
            confirmDeleteBtn.disabled = false;
            confirmDeleteBtn.textContent = '确认注销';
            // 清空密码框
            document.getElementById('confirmPassword').value = '';
        });
    });
</script>
</body>
</html>